const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const _ = db.command
const config = require('./config')
const Tenpay = require('tenpay');
const crypto = require('crypto'); 

// 初始化微信支付
const tenpay = new Tenpay({
  appid: config.appId,
  mchid: config.mchId,
  partnerKey: config.mchKey,
  notify_url: config.notifyUrl,
  spbillCreateIp: '127.0.0.1'
})

// 云函数入口函数
exports.main = async (event, context) => {
  const { action, orderInfo } = event
  const wxContext = cloud.getWXContext()
  
  try {
    switch (action) {
      case 'unifiedOrder':
        return await handleUnifiedOrder(orderInfo, wxContext)
      default:
        return { success: false, message: '未知操作' }
    }
  } catch (error) {
    console.error('微信支付错误:', error)
    return { success: false, message: error.message || '操作失败' }
  }
}

// 统一下单处理
async function handleUnifiedOrder(orderInfo, wxContext) {
  try {
    // 参数检查
    if (!orderInfo.goodsId || !orderInfo.goodsName || !orderInfo.price) {
      throw new Error('订单信息不完整')
    }
    
    // 生成订单号
    const outTradeNo = `ORD_${Date.now()}_${Math.floor(Math.random() * 1000)}`
    
    // 调用统一下单
    const result = await tenpay.getPayParams({
      body: orderInfo.goodsName,
      out_trade_no: outTradeNo,
      total_fee: Math.floor(orderInfo.price * 100),
      spbill_create_ip: wxContext.CLIENTIP || '127.0.0.1',
      trade_type: 'JSAPI',
      openid: wxContext.OPENID
    })
    
    console.log('统一下单结果:', result)
    
    // 生成支付参数
    const payParams = tenpay.getPayParams(result)
    console.log('自动生成的支付参数:', payParams)
    
    // 手动生成签名进行验证
    const manualSign = generateSign(
      {
        appId: payParams.appId,
        timeStamp: payParams.timeStamp,
        nonceStr: payParams.nonceStr,
        package: payParams.package,
        signType: payParams.signType
      }, 
      config.partnerKey
    )
    
    console.log('自动生成的签名:', payParams.paySign)
    console.log('手动生成的签名:', manualSign)
    console.log('签名是否一致:', payParams.paySign === manualSign)
    
    // 保存订单
    const orderData = {
      goodsId: orderInfo.goodsId,
      goodsName: orderInfo.goodsName,
      price: orderInfo.price,
      count: orderInfo.count || 1,
      addressId: orderInfo.addressId || '',
      outTradeNo: outTradeNo,
      remarks: orderInfo.remarks || '',
      openid: wxContext.OPENID,
      status: '待支付',
      payInfo: result,
      createTime: db.serverDate()
    }
    
    const orderRes = await db.collection('orders').add({ data: orderData })
    
    return {
      success: true,
      orderId: orderRes._id,
      orderNo: outTradeNo,
      payParams: payParams
    }
  } catch (error) {
    console.error('统一下单失败:', error)
    throw error
  }
}

// 手动生成签名（用于调试）
function generateSign(params, partnerKey) {
  const sortedParams = Object.keys(params)
    .sort()
    .reduce((obj, key) => {
      obj[key] = params[key]
      return obj
    }, {})
  
  let stringA = ''
  for (const key in sortedParams) {
    if (sortedParams[key]) {
      stringA += `${key}=${sortedParams[key]}&`
    }
  }
  
  const stringSignTemp = stringA + `key=${partnerKey}`
  const sign = crypto.createHash('md5')
    .update(stringSignTemp, 'utf8')
    .digest('hex')
    .toUpperCase()
    
  return sign
}